package com.we.flink.userlabelplatform.table;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;

public class TableUserCertifyCompany {
    public static final String KFKTABLE = "fdm.hhl01_user_certify_company";
    public static final String QUERYSQL =
            "select uid, "
                    + "status as is_business_license_uploaded "
                    + " from "
                    + KFKTABLE
                    + " where uid is not null "
                    + "and status is not null "
                    + "and deleted_at is null";

    public long uid;
    public int is_business_license_uploaded;

    public TableUserCertifyCompany(long uid, int is_business_license_uploaded) {
        this.uid = uid;
        this.is_business_license_uploaded = is_business_license_uploaded;
    }

    public TableUserCertifyCompany() {}

    public static TableUserCertifyCompany init(long uid) {
        return new TableUserCertifyCompany(uid, -2);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableUserCertifyCompany.QUERYSQL);
        DataStream<Tuple2<Boolean, TableUserCertifyCompany>> inputStream =
                tableEnv.toRetractStream(tableRes, TableUserCertifyCompany.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableUserCertifyCompany>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableUserCertifyCompany> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagUserCertifyCmpy-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableUserCertifyCompany>, Long>() {
                                    @Override
                                    public Long getKey(
                                            Tuple2<Boolean, TableUserCertifyCompany> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableUserCertifyCompany>, String>() {
                                    ValueState<TableUserCertifyCompany> userCertifyCompanyVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        userCertifyCompanyVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TableUserCertifyCompany>(
                                                                        "UserCertifyCompanyVState",
                                                                        TableUserCertifyCompany
                                                                                .class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableUserCertifyCompany> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        int is_business_license_uploaded =
                                                value.f1.getIs_business_license_uploaded();

                                        TableUserCertifyCompany tmpState =
                                                userCertifyCompanyVState.value();
                                        TableUserCertifyCompany curState =
                                                tmpState == null
                                                        ? TableUserCertifyCompany.init(uid)
                                                        : tmpState;

                                        /** 只要上传过认证 is_business_license_uploaded标签一直为1 */
                                        if (curState.getIs_business_license_uploaded()
                                                        != is_business_license_uploaded
                                                && curState.getIs_business_license_uploaded()
                                                        != 1) {
                                            JSONObject jsonObject = new JSONObject();
                                            jsonObject.put("uid", uid);
                                            jsonObject.put(
                                                    "is_business_license_uploaded",
                                                    is_business_license_uploaded);
                                            out.collect(jsonObject.toString());

                                            curState.is_business_license_uploaded =
                                                    is_business_license_uploaded;
                                            userCertifyCompanyVState.update(curState);
                                        }
                                    }
                                });

        return out;
    }

    public long getUid() {
        return uid;
    }

    public int getIs_business_license_uploaded() {
        return is_business_license_uploaded;
    }
}
